package jframe.xfire.factory;

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @描述:<p> </p>
 *
 * @作者: 叶平平(yepp)
 *
 * @时间: 2011-12-30 下午10:17:47
 */
public class XmlHelper implements IXmlHelper{

	private Marshaller marshaller;
	
	private Unmarshaller unmarshaller;
	
	public XmlHelper(){
		
	}
	
	public XmlHelper(Marshaller marshaller,Unmarshaller unmarshaller){
		this.setMarshaller(marshaller);
		this.setUnmarshaller(unmarshaller);
	}

	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}

	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}

	/**
	 * 将XML的String内容转换为数据模型对象
	 */
	@Override
	public Object xml2Java(String xml) {
		StringReader reader = new StringReader(xml);
		Object obj = null;
		try {
			obj = this.unmarshaller.unmarshal(reader);
		} catch (JAXBException e) {
			throw new  RuntimeException("xml2Java解析错误",e);
		}
		return obj;
	}
	
	/**
	 * 
	 */
	public Object xml2Java(File file){
		Object obj = null;
		try {
			obj = this.unmarshaller.unmarshal(file);
		} catch (JAXBException e) {
			throw new  RuntimeException("xml2Java解析错误",e);
		}
		return obj;
	}

	/**
	 * 将数据模型对象内容转换为XML文档String
	 */
	@Override
	public String java2Xml(Object obj) {
		StringWriter sw = new StringWriter();
		try{
			this.marshaller.marshal(obj, sw);
		}catch (Exception e) {
			throw new  RuntimeException("java2Xml解析错误",e);
		}
		String ret = sw.toString();
		//替换xml头部为""
		ret.replaceFirst("<\\?xml[^>]*\\?>", "");
		return ret;
	}

}
